import json
import json5


def read_json(json_path):
    """
    读取Json文件
    :param json_path: Json文件路径
    """
    if isinstance(json_path, str):
        if json_path.endswith('.json'):
            try:
                return json.load(open(json_path, encoding="utf-8", errors='ignore'))
            except ValueError:
                return json.load(open(json_path, encoding="gbk", errors='ignore'))
        else:
            try:
                return json5.load(open(json_path, encoding="utf-8", errors='ignore'))
            except ValueError:
                return json5.load(open(json_path, encoding="gbk", errors='ignore'))
    else:
        return json_path


def save_json(obj, json_path):
    """
    保存为Json文件
    :param json_path: 保存地址
    """
    if json_path.endswith('.json'):
        with open(json_path, "w", encoding="utf-8") as f:
            json.dump(obj, f, ensure_ascii=False, indent=4)
    else:
        with open(json_path, "w", encoding="utf-8") as f:
            json5.dump(obj, f, ensure_ascii=False, indent=4)


def dumps_json5(obj):
    """
    输出Json5文本
    """
    return json5.dumps(obj, ensure_ascii=False, indent=4)

